<template>
  <div class="search-container">
    <form action="/" class="searchForm">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        background="#3296fa"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result :search-text="searchText" v-if="isResultShow" />
    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <!-- 历史记录 -->
    <search-history
      v-else
      :search-his="searchHis"
      @clear-his="searchHis = []"
      @search="onSearch"
    />
  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
export default {
  neme: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  watch: {
    searchHis (value) {
      setItem('TOUTIAO_SEARCH_HIS', value)
    }
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHis: getItem('TOUTIAO_SEARCH_HIS') || []
    }
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      const index = this.searchHis.indexOf(val)
      if (index !== -1) {
        this.searchHis.splice(index, 1)
      }
      this.searchHis.unshift(val)
      console.log(this.searchHis)
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .searchForm {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
